package cros

import (
	"gitee.com/zhucheer/orange/app"
	"net/http"
	"net/url"
	"strings"
)

// Handler 实现Cros中间件
type Handler struct {
	DomainList []string
}

// NewHandler 实例化中间件
func NewHandler(domainList ...string) *Handler {
	return &Handler{domainList}
}

// Func implements Middleware interface.
func (w Handler) Func() app.MiddlewareFunc {
	return func(next app.HandlerFunc) app.HandlerFunc {
		return func(c *app.Context) error {
			referer := c.OrangeInput.Header("Origin")
			u, _ := url.Parse(referer)

			allowOrigin := ""
			// 域名在范围内则允许跨域操作
			if u.Host != "" {
				for _, allow := range w.DomainList {
					allow = strings.Replace(allow, "*.", "", 1)
					if strings.Contains(u.Host, allow) {
						allowOrigin = referer
						break
					}
				}
			}

			if allowOrigin != "" {
				// 跨域配置
				c.ResponseHeader().Set("Access-Control-Allow-Origin", allowOrigin)
				c.ResponseHeader().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
				c.ResponseHeader().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
				c.ResponseHeader().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
				c.ResponseHeader().Set("Access-Control-Allow-Credentials", "true")
			}
			if c.OrangeInput.Method() == "OPTIONS" {
				c.SetResponseStatus(http.StatusNoContent)
				return nil
			}

			return next(c)
		}
	}
}
